from pyfoo import *
from AbstractWrapper import AbstractWrapper

class WufooWrapper(AbstractWrapper):
    """ A wrapper that uses the Pyfoo API to connect to a Wufoo data source """
    schema = {}
    
    def __init__(self, config, key):
        super(WufooWrapper, self).__init__(config)
        self.key = key
        self.setSchema()

    def getConnection(self):
        return PyfooAPI(self.config['username'], self.config['password'])

    def setSchema(self):
        self.schema["name"] = self.config["name"]
        self.schema["tables"] = []
 
        api = self.getConnection()
        for form in api.forms:
            table = {"tablename" : form.Name,
                     "key" : self.key,
                     "fields" : []}
            
            # Don't add this form if it doesn't contain our join key
            if self.key not in [field.Title for field in form.fields]:
                print("Wufoo Wrapper Warning: excluded form '" + form.Name + "' because it doesn't contain field '" + self.key + "'")
                print("Fields in this form: "+ str([field.Title for field in form.fields]))
                continue

            for field in form.fields:
                table["fields"].append({"fieldname" : field.Title,
                            "alternate" : field.Title})

            self.schema["tables"].append(table)


    def getSchema(self):
        """ Returns a dictionary representing this data source's schema """
        return self.schema
    
    def query(self, db):
        """
        Takes a dictionary in Reswell Query format and makes the
        appropriate Wufoo API calls
        """
        api = self.getConnection()
        tables = []
        filters = []
        fields = []
        for table in db['tables']:
            tables.append(table['name'])
            #filters += table['filters']
            #fields += table['fields']

        #make url parameters from filters
        convert = {'>': 'Is_greater_than', '<': 'Is_less_than',
                   '=': 'Is_equal_to', '==': 'Is_equal_to',
                   '!=': 'Is_not_equal_to'}

        data = dict()
        numFields = 0
        for form in api.forms:
            if(form.Name in tables):
                filters = []
                fields = []
                for table in db['tables']:
                    if(table['name'] == form.Name):
                        filters = table['filters']
                        fields = table['fields']
                parameters = map(lambda f: SearchParameter(f['left'], convert[f['op']], f['right']), filters)
                try:
                    if len(filters) == 0:
                        entries = form.get_entries()
                    else:
                        entries = form.search_entries(parameters)
                except:
                    entries = []
                for entry in entries:
                    myid = form.get_field(self.key)
                    if entry[myid.ID] not in data:
                        data[entry[myid.ID]] = ['']*numFields
                        
                    #data[entry[myid.ID]] = [] #instantiate myid for everyone
                    for fieldName in fields: #fields user wants
                        field = form.get_field(fieldName)
                        if field:
                            #add data entry to each myid 
                            data[entry[myid.ID]].append(entry[field.ID])
                numFields += len(fields)
                for key in data.keys():
                    if len(data[entry[myid.ID]]) == numFields-1:
                        data[entry[myid.ID]].append('')
        print(data)
        return data
